import { Form, Input, message, Modal } from 'antd';

import noticeService from '@/api/services/setting/noticeService';
import userService from '@/api/services/security/userService';
import Editor from '@/components/editor';
import UploadPicture from '@/components/upload-picture';

import { NoticeType } from './type';

import { ModalProps } from '#/entity';

export default function IndexModal({
  title,
  show,
  onOk,
  onCancel,
  formValue,
}: ModalProps<NoticeType>) {
  const [form] = Form.useForm();
  const onUploadSuccess = (fileId) => {
    form.setFieldsValue({
      cover: fileId[0],
    });
  };
  const onFinish = (values) => {
    values.userId = values.user?.id;
    if (formValue.id) {
      noticeService.update(formValue.id, values).then(() => {
        message.success('修改成功');
        onOk();
      });
    } else {
      noticeService.create(values).then(() => {
        message.success('新增成功');
        onOk();
      });
    }
  };
  const userInfo = async (qs: string) => {
    const res = await userService.getUserList({ take: 10, page: 1, name: qs });
    return res.data.map((item): any => ({
      label: item.name,
      value: item.id,
    }));
  };
  // __________________________________________________________________
  const titleMaxLength = 64;
  const contentMaxLength = 256;
  const modalRender = (dom: React.ReactNode) => (
    <Form
      initialValues={formValue}
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      onFinish={onFinish}
      clearOnDestroy
      layout="horizontal"
    >
      {dom}
    </Form>
  );
  return (
    <Modal
      width={1400}
      style={{ top: 20 }}
      styles={{
        body: {
          overflowY: 'auto',
          maxHeight: 'calc(100vh - 200px)',
          paddingBottom: '20px',
        },
      }}
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
      destroyOnClose
      modalRender={modalRender}
    >
      <Form.Item name="cover" label="封面" rules={[{ required: true }]}>
        <UploadPicture
          onUploadSuccess={onUploadSuccess}
          portraitList={formValue.cover ? [formValue.cover] : []}
        />
      </Form.Item>
      <Form.Item
        label="标题"
        name="title"
        rules={[
          { required: true },
          {
            max: titleMaxLength,
            message: `标题不能超过 ${titleMaxLength} 个字符`,
          },
        ]}
      >
        <Input showCount maxLength={titleMaxLength} />
      </Form.Item>
      <Form.Item label="内容" name="content" rules={[{ required: true }]}>
        <Editor />
      </Form.Item>
      {/* <Form.Item label="跳转链接" name="source" rules={[{ required: true }]}>
        <Input />
      </Form.Item> */}
      <Form.Item label="备注" name="remark">
        <Input.TextArea />
      </Form.Item>
    </Modal>
  );
}
